//
//  SNHomePageViewController.m
//  project
//
//  Created by 黄建华 on 2017/11/20.
//  Copyright © 2017年 黄建华. All rights reserved.
//
#import "SNHomePageViewController.h"
#import "CalendarViewController.h"
#import "CalendarButton.h"
#import "SNHomePageTableViewCell.h"
#import "SNStepChartVc.h"
#import "SNSleepDetailVc.h"
#import "SNHearDetailVc.h"
#import "SNBpDetailVc.h"
#import "SNOxDetailVc.h"
#import "FSCalendar.h"
#import "SNHealthyCheckVc.h"
#import "SNHomeHeadView.h"
#import "project-Swift.h"
#import "WeatherModel.h"
#import "DertView.h"
#import "SNFoodViewController.h"
#import "SNFoodDetailViewController.h"
#import "SNFoodSettingViewController.h"
#import "SNSortFriendVc.h"
#import "SNSportViewController.h"
#import "SportModeModel.h"
#import "SNHomeModel.h"
#import "SNHomeCollectionViewCell.h"

//#define  footHeight  12.0
//#define  footHeight HHHWIDTH / 2.0 * FitSimpleSize(0.8, 0.8, 0.58, 0.7, 0.7)
#define  footHeight HHHWIDTH / 2.0 * FitSimpleSize(0.8, 1, 1, 1, 1)
@interface SNHomePageViewController () <UITableViewDelegate, UITableViewDataSource, FSCalendarDelegate, FSCalendarDataSource, FSCalendarDelegateAppearance, UIScrollViewDelegate, UIGestureRecognizerDelegate, UICollectionViewDelegate, UICollectionViewDataSource>{
    //日历控件
    FSCalendar *_calendar;
    //
}

@property (nonatomic, strong) ZZCACircleProgress            *stepCircle; // 步数圆圈
@property (nonatomic, strong) UIButton                      *stepDetailButton;
@property (nonatomic, strong) UILabel                       *currentDateLabel; // 当前日期
@property (nonatomic, strong) CalendarButton                *calendarBtn; // 日历按钮
@property (nonatomic, strong) UIView                        *calendarView;
@property (nonatomic, strong) CalendarViewController        *CalendarViewSub;
@property (nonatomic, strong) UIButton                      *detailChartButton;
@property (nonatomic, strong) SNCustomLabel                 *distanceLabel;
@property (nonatomic, strong) SNCustomLabel                 *StepLabel;
@property (nonatomic, strong) SNCustomLabel                 *calorLabel;
@property (nonatomic, strong) SNHomePageShowStepDetailLabel *distanceUnitLabel;
@property (nonatomic, strong) SNHomePageShowStepDetailLabel *stepUnitLabel;
@property (nonatomic, strong) SNHomePageShowStepDetailLabel *calorUnitLabel;

@property (nonatomic, strong) UIScrollView            *headView;      //下拉视图
@property (nonatomic, strong) UITableView             *tableView;
@property (nonatomic, strong) NSMutableArray          *dataArray;
@property (nonatomic, strong) NSMutableArray          *pushArray;
@property (nonatomic, strong) NSMutableArray          *originalDataArray;
@property (nonatomic, strong) SNHomeHeadView          *leftView;
@property (nonatomic, strong) SNHomeHeadView          *centerView;
@property (nonatomic, strong) SNHomeHeadView          *rightView;
@property (nonatomic, strong) UIImageView             *animateView;
@property (nonatomic, strong) UIView                  *bgView;
@property (nonatomic, assign) BOOL                    isUpdateView;
@property (nonatomic, strong) MJRefreshNormalHeader   *header;
@property (nonatomic, strong) NSString                *weatherType;
@property (nonatomic, strong) SNClickEffView          *clickView;
@property (nonatomic, strong) UIView                  *footView;
@property (nonatomic, strong) UILabel                 *foodValuelabel;
@property (nonatomic, strong) UILabel                 *foodEatInfoLabel;
@property (nonatomic, strong) SNShadowView            *footViewInfo;
@property (nonatomic, strong) UICollectionView        *collectionView;
@property (nonatomic, strong) UIButton                *editButton;
@property (nonatomic, assign) BOOL                    edit;
@property (nonatomic, strong) SNCustomLabel           *weatherLabel;
@property (nonatomic, strong) UIImageView             *weatherImageV;
@property (nonatomic, strong) SNCustomLabel           *weatherTypeLabel;
@property (nonatomic, strong) UIButton                *foodSetView1;
@property (nonatomic, strong) UIView                  *weatherBakeView;
@property (nonatomic, assign) BOOL                    isReload;
@end

@implementation SNHomePageViewController

- (void)delayUpdateWeather {
    [KK_WeatherModel startUpdateLocation];
}

// 更新闹钟的状态
- (void)resetAlarmClock
{
    NSArray *array = SN_USER.showAlarmArray;
    NSArray  *arr = @[HHH_Text(@"周一,"), HHH_Text(@"周二,"), HHH_Text(@"周三,"), HHH_Text(@"周四,"), HHH_Text(@"周五,"), HHH_Text(@"周六,"), HHH_Text(@"周日,")];
    for (SNAlarmModel *model in array) {
        NSString *str = [NSString stringWithFormat:@"%@%@%@%@%@%@%@", model.MON ? arr[0] : @"", model.TUE ? arr[1] : @"", model.WED ? arr[2] : @"", model.THU ? arr[3] : @"", model.FRI ? arr[4] : @"", model.SAT ? arr[5] : @"", model.SUN ? arr[6] : @""];
        if (str.length > 0) {
            
        } else {
            NSDate *date = [NSDate date];
            if ([date compareWithDate:model.date]) {
                if ([date compare:model.date] == 1 && model.open) {
                    model.open = NO;
                    [SN_USER.showAlarmArray replaceObjectAtIndex:model.orderIndex withObject:model];
                    for (int i = 0; i < SN_USER.showAlarmArray.count; i++) {
                        [SN_USER.alarmArray replaceObjectAtIndex:i withObject:SN_USER.showAlarmArray[i]];
                    }
                    [SN_USER updateToDB];
                }
            } else {
                if ([[NSDate dateByString:date.dateToDayString] dateByDistanceDaysWithDate:[NSDate dateByString:model.date.dateToDayString]] == 1) {
                }
                else if ([[NSDate dateByString:date.dateToDayString] dateByDistanceDaysWithDate:[NSDate dateByString:model.date.dateToDayString]]<0){
                    model.open = NO;
                    [SN_USER.showAlarmArray replaceObjectAtIndex:model.orderIndex withObject:model];
                    for (int i = 0; i < SN_USER.showAlarmArray.count; i++) {
                        [SN_USER.alarmArray replaceObjectAtIndex:i withObject:SN_USER.showAlarmArray[i]];
                    }
                    [SN_USER updateToDB];
                }
                else {
                }
            }
        }
    }
}


- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self resetAlarmClock];
    
    _dataArray = [[NSMutableArray alloc] init];
    _originalDataArray = [NSMutableArray array];
    
    _edit = NO;
    [self delayUpdateWeather];
    [self addNavView];
    [self initTabelView];
    [self initCollecionView];
    //[SN_Net uploadUserLog];
    
    UIImageView *shadowLine = [[UIImageView alloc] init];
    shadowLine.frame = SNFRAME(0, 20+FitSimpleIpx(0, 20) + 44 -2, HHHWIDTH, 2);
    shadowLine.image = [UIImage image:@"lineImage"];
    [self.view addSubview:shadowLine];
    
    DEF_WEAKSELF_(SNHomePageViewController)
    
    if (!_calendarView) {
        _calendarView        = [[UIView alloc] init];
        _calendarView.frame  = SNFRAME(0, 220, HHHWIDTH, 440);
        _calendarView.hidden = YES;
        [self.view addSubview:_calendarView];
    }
    
    if (!_CalendarViewSub) {
        _CalendarViewSub = [[CalendarViewController alloc] init];
        [_calendarView addSubview:_CalendarViewSub.view];
        _calendarView.transform         = CGAffineTransformMakeScale(0.9f, 0.9f);
        _CalendarViewSub.view.transform = CGAffineTransformMakeScale(0.9f, 0.9f);
    }
    _CalendarViewSub.selectDateBlock = ^(NSDate *date) {
        
        SN_PublicClass.selectDate      = date;
        weakSelf.currentDateLabel.text = [SN_PublicClass showDateWithType:0];
        [weakSelf.calendarView dismissPopup];
        [weakSelf updateAlldata];
        [weakSelf updateTableView];
    };
    _CalendarViewSub.cancelBlock = ^()
    {
        [weakSelf.calendarView dismissPopup];
    };
    [[BackGroundTaskView sharedInstance] checkAppVersionUpdate];
    [SN_Net getAppUpdateInfoFromServerWithSuccess:^(id object) {
    } fail:^(id object) {
    }];
    
    SN_PublicClass.weatherBlock = ^(){
        [weakSelf updateWeateherTextLabel];
    };
    
}

- (void)updateWeateherTextLabel {
    _weatherImageV.image   = [self backImage];
    _weatherTypeLabel.text = _weatherType;
    if (SN_USER.temperatureSet) {
        _weatherLabel.text = [NSString stringWithFormat:@"%d-%d℉", (int)(KK_WeatherModel.minTem.integerValue *1.8+32), (int)(KK_WeatherModel.maxTem.integerValue *1.8+32)];
    } else {
        _weatherLabel.text = [NSString stringWithFormat:@"%@-%@℃", KK_WeatherModel.minTem, KK_WeatherModel.maxTem];
    }
}

- (void)SNBecomeActive {
    // 每间隔30分钟
    if ([[NSUserDefaults standardUserDefaults] objectForKey:@"queryDataTime"]) {
        NSInteger second = [NSDate intervalSecondsWithSmallDate:[[NSUserDefaults standardUserDefaults] objectForKey:@"queryDataTime"] bigDate:[NSDate date]];
        if (second >= 1800) {
            //            [kK_App latestRealSportDataNotification:@"间隔30分钟同步大数据" subtitle:@"" identifier:@"SynchronousBigDatas"];
            [[NSUserDefaults standardUserDefaults] setObject:[NSDate date] forKey:@"queryDataTime"];
            // 全部数据刷新
            [KK_BLESend sendCMD];
        }
    } else {
        [[NSUserDefaults standardUserDefaults] setObject:[NSDate date] forKey:@"queryDataTime"];
    }
    [self updateAlldata];
    [self updateTableView];
    [self updateFoodValueLabel];
    
    _isUpdateView = YES;
    
}

- (void)SNBebackground {
    _isUpdateView = NO;
    _edit = NO;
    [self editArrayFinish];
    // 刷新
    NSInteger row                      = _dataArray.count/2 + _dataArray.count %2;
    CGFloat   height                   = row * (HHHWIDTH / 2.0) + 20;
    _collectionView.frame = SNFRAME(0, _footView.bottom, HHHWIDTH, height);
    
    [_tableView reloadData];
    [_collectionView reloadData];
}

- (void)updateFoodValueLabel {
    // asdfa
    NSInteger currentCalor = SN_PublicClass.todayFood.currentCalor;
    NSInteger calorTarget  = 1.1*SN_PublicClass.todayFood.goal_calory;
    
    if (calorTarget == 0) {
        NSInteger bmr = 0;
        if (SN_USER.gender == 1) {
            bmr = 10*SN_USER.weight +6.25*SN_USER.height - 5*SN_USER.age +5;
        } else {
            bmr = 10*SN_USER.weight +6.25*SN_USER.height - 5*SN_USER.age -161;
        }
        calorTarget = 1.1*bmr;
    }
    //    calorTarget = [KK_ShareData getNumberWith: calorTarget];
    
    if (_foodValuelabel) {
        _foodValuelabel.text = [NSString stringWithFormat:@"%ld/%ld %@", (long)currentCalor, (long)calorTarget, SN_Text(@"大卡")];
        NSMutableAttributedString *noteStr;
        NSString                  *text1 = StrByInt(currentCalor);
        noteStr = [[NSMutableAttributedString alloc] initWithString:_foodValuelabel.text];
        if (currentCalor > calorTarget) {
            if (text1.length > 0) {
                NSUInteger first1 = [[noteStr string] rangeOfString:text1].location;
                NSRange    range  = NSMakeRange(first1, text1.length);
                [noteStr addAttribute:NSForegroundColorAttributeName value:FOODCOLOR range:range];
            }
        }
        
        NSString *text2 = SN_Text(@"大卡");
        if (text2.length > 0) {
            NSInteger first1 = [[noteStr string]rangeOfString:text2].location;
            NSRange   range  = NSMakeRange(first1, text2.length);
            [noteStr addAttribute:NSFontAttributeName value:[UIFont fontWithName:@"Helvetica-Bold" size:13] range:range];
        }
        
        [_foodValuelabel setAttributedText:noteStr];
    }
    
    NSInteger count = SN_PublicClass.todayFood.count;
    if (count == 0) {
        _foodEatInfoLabel.text = [NSString stringWithFormat:@"%@", SN_Text(@"未记录用餐")];
    } else {
        _foodEatInfoLabel.text = [NSString stringWithFormat:@"%@:%ld %@ %@", SN_Text(@"已记录"), (long)count, SN_Text(@"餐"), SN_PublicClass.todayFood.lastTime];
        if (_foodEatInfoLabel != nil) {
            _foodEatInfoLabel.numberOfLines = 0;
            NSDictionary *attribute1 = @{NSFontAttributeName: _foodEatInfoLabel.font};
            //计算实际frame大小，并将label的frame变成实际大小
            CGSize labelsize1 = [_foodEatInfoLabel.text boundingRectWithSize:CGSizeMake(_foodSetView1.width, MAXFLOAT) options:NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading attributes:attribute1 context:nil].size;
            _foodEatInfoLabel.frame = CGRectMake(0, _foodSetView1.height - 34, labelsize1.width, labelsize1.height);
        }
    }
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
//    [self performSelector:@selector(SNBecomeActive) withObject:nil afterDelay:0.2f];
    if (_clickView) {
        [_clickView removeFromSuperview];
        _clickView = nil;
    }
    [self updateFoodValueLabel];
    
    if (SN_USER.goal_weight == 0) {
        _footViewInfo.hidden = NO;
    } else {
        _footViewInfo.hidden = YES;
    }
    
    SN_PublicClass.isMainEdit = NO;
    _edit                 = NO;
//    [self updateTableView];
    [_editButton setTitle:SN_Text(@"编辑") forState:UIControlStateNormal];
    
    [self updateWeateherTextLabel];
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [[self class] cancelPreviousPerformRequestsWithTarget:self selector:@selector(SNBecomeActive) object:nil];
    [[self class] cancelPreviousPerformRequestsWithTarget:self selector:@selector(delayUpdateWeather) object:nil];
}

- (void)addNavView {
    UIView *naView = [[UIView alloc] init];
    
    naView.frame           = CGRectMake(0, 20+FitSimpleIpx(0, 20), kSCREEN_WIDTH, 44);
    naView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:naView];
    
    _calendarBtn                 = [[CalendarButton alloc] initWithFrame:SNFRAME(0, 0, 44, 44)];
    _calendarBtn.imageEdgeInsets = UIEdgeInsetsMake(0, 0, 2, 0);
    [_calendarBtn addTarget:self action:@selector(crectCalendar) forControlEvents:UIControlEventTouchUpInside];
    [naView addSubview:_calendarBtn];
    
    _currentDateLabel               = [[UILabel alloc] initWithFrame:SNFRAME(0, (44-25)/2.0, HHHWIDTH, 25)];
    _currentDateLabel.textColor     = SNCOLORBLACK;
    _currentDateLabel.textAlignment = NSTextAlignmentCenter;
    _currentDateLabel.font          = SNFONT(20.0);
    [naView addSubview:_currentDateLabel];
    _calendarBtn.center = CGPointMake(26, _currentDateLabel.center.y);
    
    UIButton *backButton = [[UIButton alloc] init];
    backButton.frame  = SNFRAME(0, 0, 100, 33);
    backButton.center = _currentDateLabel.center;
    [backButton addTarget:self
                   action:@selector(backButtonClick)
         forControlEvents:UIControlEventTouchUpInside];
    [naView addSubview:backButton];
    
    _detailChartButton       = [UIButton buttonWithType:UIButtonTypeCustom];
    _detailChartButton.frame = CGRectMake(screenWidth - 44 - 5, 0, 44, 44);
    [_detailChartButton setImageNormal:@"数据"];
    _detailChartButton.imageEdgeInsets = UIEdgeInsetsMake(2, 2, 4, 2);
    [_detailChartButton addTarget:self
                           action:@selector(detailChartButtonClick)
                 forControlEvents:UIControlEventTouchUpInside];
    [naView addSubview:_detailChartButton];
    _detailChartButton.center = CGPointMake(screenWidth - 44 - 5 + 22, _currentDateLabel.center.y);
}

#pragma mark --- 应用切换到前台模式 ---

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
    if (![scrollView isKindOfClass:[UITableView class]]) {
        [self reloadScrollView];
        //移动到中间
        _headView.contentOffset = CGPointMake(HHHWIDTH, 0);
    }
}

- (void)reloadScrollView {
    CGPoint offset = [_headView contentOffset];
    
    if (offset.x > HHHWIDTH) { //向左滑动
        NSDate *nextDate = [SN_PublicClass.selectDate dateAfterDay:+1];
        [self goToDay:nextDate];
    } else if (offset.x < HHHWIDTH) { //向右滑动
        NSDate *beforeDate = [SN_PublicClass.selectDate dateAfterDay:-1];
        [self goToDay:beforeDate];
    }
}

- (void)goToDay:(NSDate *)date {
    NSInteger nowCount = [NSDate compareDate:[NSDate date] withAnotherDay:date];
    
    if (nowCount == 1) {
        SHOWMBProgressHUD(nil, SN_Text(@"不能选择未来时间！"), nil, NO, 1.0);
        return;
    }
    SN_PublicClass.selectDate = date;
    [self updateAlldata];
    [self updateTableView];
}

// 更新当前所有UI显示
- (void)updateAlldata {
    //主页日期
    _calendarBtn.selectDateLabel.text = SNSTRING(@(SN_PublicClass.selectDate.day));
    _currentDateLabel.text            = [SN_PublicClass showDateWithType:0];
    
    SportModel *leftModel = [SportModel getSportModelFromDBWith:[SN_PublicClass.selectDate dateAfterDay:-1]];
    _leftView.model = leftModel;
    
    SportModel *centerModel = [SportModel getSportModelFromDBWith:SN_PublicClass.selectDate];
    _centerView.model = centerModel;
    
    SportModel *rightModel = [SportModel getSportModelFromDBWith:[SN_PublicClass.selectDate dateAfterDay:+1]];
    _rightView.model = rightModel;
}

// 入口 1:日期选择或者 2:蓝牙同步完刷新这里
- (void)updateTableView {
    [_originalDataArray removeAllObjects];
    [_dataArray removeAllObjects];
    // 初始化数据
    __weak typeof(self) weakSelf = self;
    if ([[NSUserDefaults standardUserDefaults] objectForKey:@"isHadRequestBleFunction"] == NO) {
        // 获取设备支持相关功能
        [SN_Net getDeviceSFromServerWithSuccess:^(id object) {
            __strong typeof(weakSelf) strongSelf = weakSelf;
            // 初始化数据源
            [strongSelf initData];
        } fail:^(id object) {
            
        }];
    } else {
        [self initData];
    }
    
    SN_Net.block = ^(BOOL isSupportFood) {
        NSLog(@"在线信息回调:%d",SN_USER.isSupporFood);
        __strong typeof(self) strongSelf = weakSelf;
        [strongSelf initOtherUi];
    };

}

// 初始化所有的功能数据源
- (void)initData {
    [_dataArray addObject:[self sleepRecordModel]];
    // 睡眠 体检 心率 血氧 血压(默认第一个都是睡眠页)
    _pushArray = [NSMutableArray array];
    [_pushArray addObject:@"0"];
    // 连接设备
    if (KK_BLEConnect.isBoindDevice) {
        // 通用
        if (SN_USER.heart || SN_USER.oxygen || SN_USER.bistoryPressure) {
            [_dataArray addObject:[self checkModel]];
            [_pushArray addObject:@"1"];
        }
        if (SN_USER.heart) {
            [_dataArray addObject:[self heartRateModel]];
            [_pushArray addObject:@"2"];
        }
        if (SN_USER.bistoryPressure) {
            [_dataArray addObject:[self bpmModel]];
            [_pushArray addObject:@"4"];
        }
        if (SN_USER.oxygen) {
            [_dataArray addObject:[self oxModel]];
            [_pushArray addObject:@"3"];
        }
        if (SN_USER.isSupportSportMode) {
            [_dataArray insertObject:[self sportModeModel] atIndex:1];
            [_pushArray addObject:@"5"];
        }
        //兼容
        if (_pushArray.count == 1) {
            [SN_Net getDeviceSFromServerWithSuccess:nil fail:nil];
            if ([KK_BLEModel.bleName isEqualToString:@"X10pro"] || [KK_BLEModel.bleName isEqualToString:@"X10Pro"] || [KK_BLEModel.bleName isEqualToString:@"X10plus"] || [KK_BLEModel.bleName isEqualToString:@"X10Plus"]) {
                [_dataArray addObject:[self checkModel]];
                [_pushArray addObject:@"1"];
                [_dataArray addObject:[self heartRateModel]];
                [_pushArray addObject:@"2"];
                [_dataArray addObject:[self bpmModel]];
                [_pushArray addObject:@"4"];
                [_dataArray addObject:[self oxModel]];
                [_pushArray addObject:@"3"];
            }
        }
    } else {
        [_dataArray addObject:[self checkModel]];
        [_pushArray addObject:@"1"];
        [_dataArray addObject:[self heartRateModel]];
        [_pushArray addObject:@"2"];
        [_dataArray addObject:[self bpmModel]];
        [_pushArray addObject:@"4"];
        [_dataArray addObject:[self oxModel]];
        [_pushArray addObject:@"3"];
    }
    
    SN_PublicClass.function = [NSMutableArray arrayWithArray:_pushArray];
    
    [_dataArray insertObject:[self healthDayModel] atIndex:0];
    
    // 保存数据源(编辑操作主要记录SNHomModel的tag)
    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
    [_originalDataArray addObjectsFromArray:_dataArray];
    
    NSArray *showTagArray = [userDefaults objectForKey:@"showTagArray"];
    // 解绑设备时移除@"orderTagArray"的保存
    NSArray *orderTagArray = [userDefaults objectForKey:@"orderTagArray"];
    
    if (orderTagArray.count != 0) {
        NSMutableArray *willShowArray = [NSMutableArray array];
        // 顺序
        for (int i = 0; i <orderTagArray.count; i++) {
            int index = [orderTagArray[i] intValue];
            for (SNHomeModel *model in _dataArray) {
                if (model.tag == index) {
                    [willShowArray addObject:model];
                }
            }
        }
        // 显示
        NSMutableArray *didShowArray = [NSMutableArray array];
        for (int i = 0; i< showTagArray.count; i++) {
            int index = [showTagArray[i] intValue];
            for (SNHomeModel *model in willShowArray) {
                if (model.tag == index) {
                    [didShowArray addObject:model];
                }
            }
        }
        
        // 保存剩下的
        NSMutableArray *otherArray = [NSMutableArray array];
        [otherArray addObjectsFromArray:_dataArray];
        [otherArray removeObjectsInArray:didShowArray];
        
        NSMutableArray *tagArray = [NSMutableArray array];
        for (SNHomeModel *model in otherArray) {
            [tagArray addObject:@(model.tag)];
        }
        NSArray *array = tagArray;
        [userDefaults setObject:array forKey:@"hideTagArray"];
        
        [_dataArray removeAllObjects];
        [_dataArray addObjectsFromArray:didShowArray];
    }
    
    // 赋值顺序号
    for (int i = 0; i < _dataArray.count; i++) {
        SNHomeModel *model = _dataArray[i];
        model.order = i;
    }
    
    NSInteger row                      = _dataArray.count/2 + _dataArray.count %2;
    CGFloat   height                   = row * (HHHWIDTH / 2.0) + 20;
    _collectionView.frame = SNFRAME(0, _footView.bottom, HHHWIDTH, height);
    [_collectionView reloadData];
    [_tableView reloadData];
    
    // 标识已经请求过
    [[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"isHadRequestBleFunction"];
    [[NSUserDefaults standardUserDefaults] synchronize];
    
}

- (SNHomeModel *)healthDayModel{
    // 健康日报
    SNHomeModel *healthDayModel = [[SNHomeModel alloc] init];
    healthDayModel.imageName = @"健康顾问";
    healthDayModel.value = @"";
    healthDayModel.valueDes = @"";
    healthDayModel.hrAvg = @"";
    healthDayModel.functionTitle = SN_Text(@"健康日报");
    healthDayModel.tag = 0;
    return healthDayModel;
}

- (SNHomeModel *)sportModeModel {
    // 运动模式
    // 获取选择时间的运动降序排列的数据
    NSArray *array = [SportModeModel getDetailDataWithDay];
    SportModeModel *model = array.firstObject;
    NSString *last = @"";
    NSString *imageStr = @"icon_sport1_jianbu";
    // 判断最后一次的运动类型
    if (model.sportMode == 0) {
        
    } else if (model.sportMode == 1) {
        last = SN_Text(@"健步");
        imageStr = @"icon_sport1_jianbu";
    } else if (model.sportMode == 2) {
        last = SN_Text(@"跑步");
        imageStr = @"icon_sport1_paobu";
    } else if (model.sportMode == 3) {
        last = SN_Text(@"登山");
        imageStr = @"icon_sport1_dengshan";
    } else if (model.sportMode == 4) {
        last = SN_Text(@"骑行");
        imageStr = @"icon_sport1_qixing";
    } else if (model.sportMode == 5) {
        last = SN_Text(@"乒乓球");
        imageStr = @"icon_sport1_ppq";
    } else if (model.sportMode == 6) {
        last = SN_Text(@"篮球");
        imageStr = @"icon_sport1_lanqiu";
    } else if (model.sportMode == 7) {
        last = SN_Text(@"足球");
        imageStr = @"icon_sport1_zuqiu";
    } else if (model.sportMode == 8) {
        last = SN_Text(@"羽毛球");
        imageStr = @"icon_sport1_ymq";
    } else if (model.sportMode == 9) {
        last = SN_Text(@"跑步机");
        imageStr = @"icon_sport1_paobuji";
    } else if (model.sportMode == 10) {
        last = SN_Text(@"网球");
        imageStr = @"icon_sport1_wangqiu";
    } else if (model.sportMode == 11) {
        last = SN_Text(@"游泳");
        imageStr = @"icon_sport2_youyong";
    } else {
        imageStr = @"icon_sport1_jianbu";   // 默认健步图标
    }
    
    NSString *value = @"";        // 最后一次的运动类型名称
    NSString *valueDes = @"";     // 时长描述
    NSString *hrAvg = @"";        // 心率的描述值
    if (array.count !=0) {
        value = [NSString stringWithFormat:@"%@:%@",SN_Text(@"最后一次"),last];
        NSString *time = [self timeFormatted:(int)model.timeLength * 60];
        valueDes = [NSString stringWithFormat:@"%@:%@",SN_Text(@"时长"),time];
        hrAvg = [NSString stringWithFormat:@"%@:%ld",SN_Text(@"平均心率"),(long)model.heartAve];
    } else {
        value = @"";
        valueDes = @"";
        hrAvg = @"";
    }
    
    SNHomeModel *sportModeModel = [[SNHomeModel alloc] init];
    sportModeModel.imageName = imageStr; // 默认没有最后一次的数据的话默认图标为健步
    sportModeModel.value = value;
    sportModeModel.valueDes = valueDes;
    sportModeModel.hrAvg = hrAvg;
    sportModeModel.functionTitle = SN_Text(@"运动模式");
    sportModeModel.tag = 2;
    return sportModeModel;
}


// 睡眠记录
- (SNHomeModel *)sleepRecordModel {
    // 获取睡眠数据源
    SleepModel *sleepModel     = [SleepModel getSleepModelFromDBWith:SN_PublicClass.selectDate];
    NSString   *showSleepTotal = [NSString stringWithFormat:@"%ld%@%ld%@", sleepModel.durations/60, SN_Text(@"h"), sleepModel.durations%60, SN_Text(@"mins")];
    
    NSString *quality         = @"";
    NSString *lastTime        = @"";
    NSString *showSleepDetail = [NSString stringWithFormat:@"%@: %@", SN_Text(@"睡眠质量"), SN_Text(@"暂无数据")];
    if (sleepModel.durations > 0) {
        if (sleepModel.sleepsubArray) {
            SleepSubModel *model = [sleepModel.sleepsubArray firstObject];
            quality = SN_Text(sleepModel.compareQuality);
            NSString *time = [model.subendTime componentsSeparatedByString:@" "][1];
            lastTime        = [time substringToIndex:5];
            showSleepDetail = [NSString stringWithFormat:@"%@: %@ %@", SN_Text(@"睡眠质量"), quality, lastTime];
        }
    }
    
    SNHomeModel *sleepRecordModel = [[SNHomeModel alloc] init];
    sleepRecordModel.imageName = @"睡眠新";
    sleepRecordModel.value = showSleepTotal;
    sleepRecordModel.valueDes = showSleepDetail;
    sleepRecordModel.hrAvg = @"";
    sleepRecordModel.functionTitle = SN_Text(@"睡眠记录");
    sleepRecordModel.tag = 1;
    return sleepRecordModel;
}

// 体检
- (SNHomeModel *) checkModel{
    // 我的体检
    SNHomeModel *checkModel = [[SNHomeModel alloc] init];
    checkModel.imageName = @"体检";
    checkModel.value = @"";
    checkModel.valueDes = @"";
    checkModel.hrAvg = @"";
    checkModel.functionTitle = SN_Text(@"我的体检");
    checkModel.tag = 3;
    return checkModel;
}

// 心率
- (SNHomeModel *)heartRateModel{
    // 心率
    HeartModel *heartModel     = [HeartModel getHeartModelFromDBWith:SN_PublicClass.selectDate];
    NSString   *showHeartValue = [NSString stringWithFormat:@"%ld - %ld bpm", (long)heartModel.heartMin, (long)heartModel.heartMax];
    
    NSString *hvalue          = [NSString string];
    NSString *hlastTime       = [NSString string];
    NSString *showHeartDetail = [NSString stringWithFormat:@"%@:%@", SN_Text(@"最后一次"), SN_Text(@"暂无数据")];
    if (heartModel.heartAllValueArray.count > 0) {
        hvalue          = [NSString stringWithFormat:@"%@", [heartModel.heartAllValueArray lastObject]];
        hlastTime       = [heartModel.heartAllTimeArray lastObject];
        hlastTime       = [NSString subString:hlastTime withToIndex:5];
        showHeartDetail = [NSString stringWithFormat:@"%@:%@ %@", SN_Text(@"最后一次"), hvalue, hlastTime];
    }
    
    SNHomeModel *heartRateModel = [[SNHomeModel alloc] init];
    heartRateModel.imageName = @"心率新";
    heartRateModel.value = showHeartValue;
    heartRateModel.valueDes = showHeartDetail;
    heartRateModel.hrAvg = @"";
    heartRateModel.functionTitle = SN_Text(@"心率记录");
    heartRateModel.tag = 4;
    return heartRateModel;
}

// 血氧
- (SNHomeModel *)oxModel {
    // 血氧
    OxModel  *oModel      = [OxModel getOxModelFromDBWith:SN_PublicClass.selectDate];
    NSString *showOxValue = @"0 %";
    showOxValue = [NSString stringWithFormat:@"%ld ~ %ld %%", (long)oModel.oxMin, (long)oModel.oxMax];
    
    NSString *ovalue       = [NSString string];
    NSString *olasttime    = [NSString string];
    NSString *showOxDetail = [NSString stringWithFormat:@"%@:%@", SN_Text(@"最后一次"), SN_Text(@"暂无数据")];
    if (oModel.oxsuArrayAuto.count > 0) {
        oxSubModel *model = [oModel.oxsuArrayAuto lastObject];
        ovalue       = [NSString stringWithFormat:@"%ld %%", (long)model.oxValue];
        olasttime    = [[model.updateTime componentsSeparatedByString:@" "]lastObject];
        olasttime    = [NSString subString:olasttime withToIndex:5];
        showOxDetail = [NSString stringWithFormat:@"%@:%@ %@", SN_Text(@"最后一次"), ovalue, olasttime];
    }
    SNHomeModel *oxModel =  [[SNHomeModel alloc] init];
    oxModel.imageName = @"血氧新";
    oxModel.value = showOxValue;
    oxModel.valueDes = showOxDetail;
    oxModel.hrAvg = @"";
    oxModel.functionTitle = SN_Text(@"血氧记录");
    oxModel.tag = 6;
    return oxModel;
}

// 血压
- (SNHomeModel *)bpmModel {
    // 血压
    BpModel *bpModel = [BpModel getBpModelFromDBWith:SN_PublicClass.selectDate];
    
    NSInteger max = 0;
    NSInteger min = 0;
    if (bpModel.SBPAve > bpModel.DBPAve) {
        max = bpModel.SBPAve;
        min = bpModel.DBPAve;
    } else {
        max = bpModel.DBPAve;
        min = bpModel.SBPAve;
    }
    NSString *showBPValue = [NSString stringWithFormat:@"%ld - %ld mmHg", (long)min, (long)max];
    
    NSString *bs           = [NSString string];
    NSString *blasttime    = [NSString string];
    NSString *showBpDetail = [NSString stringWithFormat:@"%@:%@", SN_Text(@"最后一次"), SN_Text(@"暂无数据")];
    if (bpModel.bpSuArray.count > 0) {
        bpSubModel *model = [bpModel.bpSuArray lastObject];
        NSInteger        max    = 0;
        NSInteger        min    = 0;
        if (model.SBPValue > model.DBPValue) {
            max = model.SBPValue;
            min = model.DBPValue;
        } else {
            max = model.DBPValue;
            min = model.SBPValue;
        }
        bs           = [NSString stringWithFormat:@"%ld - %ld", (long)min, (long)max];
        blasttime    = [[model.updateTime componentsSeparatedByString:@" "]lastObject];
        blasttime    = [NSString subString:blasttime withToIndex:5];
        showBpDetail = [NSString stringWithFormat:@"%@:%@ %@", SN_Text(@"最后一次"), bs, blasttime];
    }
    
    SNHomeModel *bpmModel =  [[SNHomeModel alloc] init];
    bpmModel.imageName = @"血压新";
    bpmModel.value = showBPValue;
    bpmModel.valueDes = showBpDetail;
    bpmModel.hrAvg = @"";
    bpmModel.functionTitle = SN_Text(@"血压记录");
    bpmModel.tag = 5;
    return bpmModel;
}

- (NSString *)timeFormatted:(int)totalSeconds{
    int minutes = (totalSeconds / 60) % 60;
    int hours = totalSeconds / 3600;
    NSString *time = @"";
    if (hours == 0) {
        time = [NSString stringWithFormat:@"%d%@", minutes,@"mins"];
    } else {
        time = [NSString stringWithFormat:@"%02d%@%d%@",hours,@"h", minutes,@"mins"];
    }
    return time;
}

- (void)initTabelView {
    _tableView                              = [[UITableView alloc]initWithFrame:CGRectMake(0, 20+FitSimpleIpx(0, 20)+44, HHHWIDTH, HHHHEIGHT -20-FitSimpleIpx(0, 20)-44-49 +20 - 20 -10) style:UITableViewStyleGrouped];
    _tableView.delegate                     = self;
    _tableView.dataSource                   = self;
    _tableView.backgroundColor              = [UIColor clearColor];
    _tableView.separatorStyle               = UITableViewCellSeparatorStyleNone;
    _tableView.showsVerticalScrollIndicator = NO;
    [self.view addSubview:_tableView];
    
    [self initWithHeadView];
    
    _tableView.tableHeaderView = _bgView;
    UIView *blackView = [[UIView alloc] init];
    blackView.frame           = CGRectMake(0, -200, HHHWIDTH, 150);
    blackView.backgroundColor = [UIColor colorFromHex:0x4b4b4b];
    [_tableView addSubview:blackView];
    [self updateMJHeadView];
    
    if (OPENMAIN) {
        UIView *editView = [[UIView alloc] init];
        editView.frame             = SNFRAME(0,0, HHHWIDTH, 50);
        editView.backgroundColor   = [UIColor clearColor];
        _tableView.tableFooterView = editView;
        
        _editButton                 = [[UIButton alloc] init];
        _editButton.frame           = SNFRAME(70, 0, HHHWIDTH - 140, 40);
        _editButton.backgroundColor = FOODCOLOR;
        [editView addSubview:_editButton];
        [_editButton setTitle:SN_Text(@"编辑") forState:UIControlStateNormal];
        [_editButton addTarget:self action:@selector(editButtonClick:) forControlEvents:UIControlEventTouchUpInside];
        _edit = NO;
    }
}

- (void)editArray {
     [_editButton setTitle:SN_Text(@"完成") forState:UIControlStateNormal];
    //显示的数据tag
    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
    NSArray *showTagArray = [userDefaults objectForKey:@"showTagArray"];
    NSArray *hideTagArray = [userDefaults objectForKey:@"hideTagArray"];
    if (showTagArray.count != 0 || hideTagArray.count != 0) {
        [_dataArray removeAllObjects];
        // 添加+数据
        for (int i = 0; i <showTagArray.count; i++) {
            int index = [showTagArray[i] intValue];
            for (SNHomeModel *model in _originalDataArray) {
                if (model.tag == index) {
                    model.add = NO;
                    [_dataArray addObject:model];
                }
            }
        }
        
        // 添加x数据
        for (int i = 0; i <hideTagArray.count; i++) {
            int index = [hideTagArray[i] intValue];
            for (SNHomeModel *model in _originalDataArray) {
                if (model.tag == index) {
                    model.add = YES;
                    [_dataArray addObject:model];
                }
            }
        }
        NSLog(@"_dataArray:%@",_dataArray);
    } else {
        NSLog(@"不编辑:%@",_dataArray);
    }
}

- (void)editArrayFinish {
    [_editButton setTitle:SN_Text(@"编辑") forState:UIControlStateNormal];
    // 遍历数据源记录编辑后（顺序、显示、隐藏）
    NSMutableArray *orderTagArray = [NSMutableArray array];
    NSMutableArray *showTagArray  = [NSMutableArray array];
    NSMutableArray *hideTagArray  = [NSMutableArray array];
    NSMutableArray *showedArray   = [NSMutableArray array];
    for (SNHomeModel *model in _dataArray) {
        if (model.add == YES) {
            //  +
            [hideTagArray addObject:@(model.tag)];
        } else {
            //  x
            [showTagArray addObject:@(model.tag)];
            [showedArray addObject:model];
        }
        // all
        [orderTagArray addObject:@(model.tag)];
    }
    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
    [userDefaults removeObjectForKey:@"showTagArray"];
    [userDefaults removeObjectForKey:@"hideTagArray"];
    [userDefaults removeObjectForKey:@"orderTagArray"];
    // 保存
    NSArray *showArray = showTagArray;
    NSArray *hideArray = hideTagArray;
    NSArray *orderArray = orderTagArray;
    [userDefaults setObject:showArray forKey:@"showTagArray"];
    [userDefaults setObject:hideArray forKey:@"hideTagArray"];
    [userDefaults setObject:orderArray forKey:@"orderTagArray"];
    [userDefaults synchronize];
    // 移除所有数据只显示要显示的数据
    [_dataArray removeAllObjects];
    [_dataArray addObjectsFromArray:showedArray];
}

- (void)editButtonClick:(UIButton *)sender {
    _edit = !_edit;
    if (_edit) {
        UILongPressGestureRecognizer *longPressGesture = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(moveAction:)];
        _collectionView.userInteractionEnabled = YES;
        [_collectionView addGestureRecognizer:longPressGesture];
        [self editArray];
    } else {
        [_collectionView removeAllGestureRecognizers];
        [self editArrayFinish];
    }
    
    NSInteger row                      = _dataArray.count/2 + _dataArray.count %2;
    CGFloat   height                   = row * (HHHWIDTH / 2.0) + 20;
    _collectionView.frame = SNFRAME(0, _footView.bottom, HHHWIDTH, height);
    
    [_tableView reloadData];
    [_collectionView reloadData];
}

#pragma mark --初始化---
- (void)initCollecionView {
    NSInteger row                      = _dataArray.count/2 + _dataArray.count %2;
    CGFloat   height                   = row * (HHHWIDTH / 2.0) + 20;
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
    layout.itemSize                    = CGSizeMake(HHHWIDTH/2.0, HHHWIDTH/ 2.0);
    layout.minimumInteritemSpacing     = 0;
    layout.minimumLineSpacing          = 0;
    layout.sectionInset                = UIEdgeInsetsMake(0, 0, 0, 0);
    layout.headerReferenceSize         = CGSizeMake(HHHWIDTH, 10);
    _collectionView                    = [[UICollectionView alloc] initWithFrame:SNFRAME(0, _footView.bottom, HHHWIDTH, height) collectionViewLayout:layout];
    [_collectionView registerNib:[UINib nibWithNibName:NSStringFromClass([SNHomeCollectionViewCell class]) bundle:nil] forCellWithReuseIdentifier:NSStringFromClass([SNHomeCollectionViewCell class])];
    _collectionView.backgroundColor    = [UIColor whiteColor];
    _collectionView.dataSource         = self;
    _collectionView.delegate = self;
    _collectionView.showsVerticalScrollIndicator = NO;
    _collectionView.scrollEnabled      = NO;
    [_tableView addSubview:_collectionView];
}

- (void)moveAction:(UILongPressGestureRecognizer *)longPress {
    //获取此次点击的坐标，根据坐标获取cell对应的indexPath
    CGPoint point = [longPress locationInView:_collectionView];
    NSIndexPath *indexPath = [self.collectionView indexPathForItemAtPoint:point];
    //根据长按手势的状态进行处理。
    switch (longPress.state) {
        case UIGestureRecognizerStateBegan:
            //当没有点击到cell的时候不进行处理
            if (!indexPath) {
                break;
            }
            //开始移动
            [_collectionView beginInteractiveMovementForItemAtIndexPath:indexPath];
            break;
        case UIGestureRecognizerStateChanged:
            //移动过程中更新位置坐标
            [_collectionView updateInteractiveMovementTargetPosition:point];
            break;
        case UIGestureRecognizerStateEnded:
            //停止移动调用此方法
            [_collectionView endInteractiveMovement];
            break;
        default:
            //取消移动
            [_collectionView cancelInteractiveMovement];
            break;
    }
}

#pragma mark ---抖动----
- (void)shakeAll {
    // 抖动
    NSArray *array = [self.collectionView visibleCells];
    for (UICollectionViewCell *cell in array) {
        CABasicAnimation *animation = (CABasicAnimation *)[cell.layer animationForKey:@"rotation"];
        if (animation == nil) {
            [self shakeView:cell];
        } else {
            [self resume:cell];
        }
    }
}

- (void)resume:(UICollectionViewCell *)aView  {
    aView.layer.speed = 1.0;
}

#define ANGLE_TO_RADIAN(angle) ((angle)/180.0 * M_PI)

- (void)shakeView:(UICollectionViewCell *)aView {
    //创建动画对象,绕Z轴旋转
    CABasicAnimation *animation = [CABasicAnimation animationWithKeyPath:@"transform.rotation.z"];
    
    //抖动角度
    //    animation.fromValue = @(-M_1_PI/2);
    //    animation.toValue = @(M_1_PI/2);
    animation.fromValue = @(ANGLE_TO_RADIAN(-2));
    animation.toValue   = @(ANGLE_TO_RADIAN(2));
    //重复次数，无限大
    animation.repeatCount = HUGE_VAL;
    //恢复原样
    animation.autoreverses = YES;
    animation.duration     = 0.1;
    //锚点设置为图片中心，绕中心抖动
    aView.layer.anchorPoint = CGPointMake(0.5, 0.5);
    [aView.layer addAnimation:animation forKey:@"rotation"];
}

#pragma mark ---UICollectionViewDelegate, UICollectionViewDataSource----

- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
    return 1;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return _dataArray.count;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    SNHomeModel *model = _dataArray[indexPath.row];
    if (_edit != YES) {
        [self pushNextViewCotroller:model.tag];
    }
}

- (void)pushNextViewCotroller:(int)tag {
    // 功能标识(0.健康日报 1.睡眠记录  2.运动模式 3.体检 4.心率记录  5.血压记录 6.血氧记录)
    if (tag == 0) {
        SNSortFriendVc *vc = [[SNSortFriendVc alloc] init];
        [self.navigationController pushViewController:vc animated:YES];
    }
    if (tag == 1) {
        SNSleepDetailVc *vc = [[SNSleepDetailVc alloc] init];
        [self.navigationController pushViewController:vc animated:YES];
    }
    if (tag == 2) {
        SNSportViewController *vc = [[SNSportViewController alloc] init];
        [self.navigationController pushViewController:vc animated:YES];
    }
    if (tag == 3) {
        SNCheckVc *vc = [[SNCheckVc alloc] init];
        [self.navigationController pushViewController:vc animated:YES];
    }
    if (tag == 4) {
        SNHearDetailVc *vc = [[SNHearDetailVc alloc] init];
        [self.navigationController pushViewController:vc animated:YES];
    }
    if (tag == 5) {
        SNBpDetailVc *vc = [[SNBpDetailVc alloc] init];
        [self.navigationController pushViewController:vc animated:YES];
    }
    if (tag == 6) {
        SNOxDetailVc *vc = [[SNOxDetailVc alloc] init];
        [self.navigationController pushViewController:vc animated:YES];
    }
}


- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    SNHomeCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:NSStringFromClass([SNHomeCollectionViewCell class]) forIndexPath:indexPath];
    [cell configWithModel:_dataArray[indexPath.row] edit:_edit];
    cell.block = ^(SNHomeModel * _Nonnull model) {
        [self editModel:model];
    };
    return cell;
}

- (void)collectionView:(UICollectionView *)collectionView moveItemAtIndexPath:(NSIndexPath *)sourceIndexPath toIndexPath:(NSIndexPath *)destinationIndexPath
{
    SNHomeModel *model = _dataArray[sourceIndexPath.item];
    [_dataArray removeObjectAtIndex:sourceIndexPath.item];
    [_dataArray insertObject:model atIndex:destinationIndexPath.item];
    
    // 赋值顺序号
//    for (int i = 0; i < _dataArray.count; i++) {
//        SNHomeModel *model = _dataArray[i];
//        model.order = i;
//    }
//
//    // 保存顺序
//    [self editArrayFinish];
    
    [UIView setAnimationsEnabled:NO];
    
    [collectionView performBatchUpdates:^{
        [collectionView reloadData];
    } completion:^(BOOL finished) {
        [UIView setAnimationsEnabled:YES];
    }];
}

- (void)editModel:(SNHomeModel *)model {
    model.add = !model.add;
    [_dataArray removeObject:model];
    int index = -1;
    int preIndex = model.order;
    if (model.add) {
        [_dataArray addObject:model];
        index = (int)(_dataArray.count - 1);
    } else {
        for (int i = 0; i < _dataArray.count; i++) {
            SNHomeModel *tmp = _dataArray[i];
            if (tmp.add) {
                index = i;
                break;
            }
        }
        if (index < 0) {
            index = (int)_dataArray.count - 1;
        }
        [_dataArray insertObject:model atIndex:index];
    }
    model.order = index;
    NSIndexPath *srcIndexPath = [NSIndexPath indexPathForItem:preIndex inSection:0];
    NSIndexPath *dstIndexPath = [NSIndexPath indexPathForItem:index inSection:0];
    [_collectionView performBatchUpdates:^{
        [self.collectionView moveItemAtIndexPath:srcIndexPath toIndexPath:dstIndexPath];
    } completion:^(BOOL finished) {
        [self.collectionView reloadData];
    }];
    
}

- (void)didSelectVc:(NSString *)selectType {
    if ([selectType isEqualToString:SN_Text(@"健康日报")]) {
        SNSortFriendVc *vc = [[SNSortFriendVc alloc] init];
        [self.navigationController pushViewController:vc animated:YES];
    }
    if ([selectType isEqualToString:SN_Text(@"睡眠记录")]) {
        SNSleepDetailVc *vc = [[SNSleepDetailVc alloc] init];
        [self.navigationController pushViewController:vc animated:YES];
    }
    if ([selectType isEqualToString:SN_Text(@"心率记录")]) {
        SNHearDetailVc *vc = [[SNHearDetailVc alloc] init];
        [self.navigationController pushViewController:vc animated:YES];
    }
    if ([selectType isEqualToString:SN_Text(@"血氧记录")]) {
        SNOxDetailVc *vc = [[SNOxDetailVc alloc] init];
        [self.navigationController pushViewController:vc animated:YES];
    }
    if ([selectType isEqualToString:SN_Text(@"血压记录")]) {
        SNBpDetailVc *vc = [[SNBpDetailVc alloc] init];
        [self.navigationController pushViewController:vc animated:YES];
    }
    if ([selectType isEqualToString:SN_Text(@"我的体检")]) {
        SNCheckVc *vc = [[SNCheckVc alloc] init];
        [self.navigationController pushViewController:vc animated:YES];
    }
    if ([selectType isEqualToString:SN_Text(@"运动模式")]) {
        SNSportViewController *vc = [[SNSportViewController alloc] init];
        [self.navigationController pushViewController:vc animated:YES];
    }
}

- (void)loadNewData {
    
    NSLog(@"开始刷新");
    if (!KK_BLESend.isSend && KK_BLEConnect.isConnected) {
        if ([[NSUserDefaults standardUserDefaults] objectForKey:@"reload"]) {
            NSInteger second = [NSDate intervalSecondsWithSmallDate:[[NSUserDefaults standardUserDefaults] objectForKey:@"reload"] bigDate:[NSDate date]];
            if (second >= 180) {
                NSLog(@">180s后开始刷新");
                [[NSUserDefaults standardUserDefaults] setObject:[NSDate date] forKey:@"reload"];
                dispatch_async(dispatch_get_main_queue(), ^{
                    _isReload = YES;
                    // 全部指令发送
                    [KK_BLESend sendCMD];
                });
                // 重置间隔30分钟查数据的逻辑计时时间
                [[NSUserDefaults standardUserDefaults] setObject:[NSDate date] forKey:@"queryDataTime"];
                [[NSUserDefaults standardUserDefaults] setObject:[NSDate date] forKey:@"reload"];
            } else {
                SHOWMBProgressHUD(nil, SN_Text(@"更新中..."), nil, NO, 2.0);
                [self endRefreshing:0.5];
            }
        } else {
            [[NSUserDefaults standardUserDefaults] setObject:[NSDate date] forKey:@"reload"];
            SHOWMBProgressHUD(nil, SN_Text(@"更新中..."), nil, NO, 2.0);
            [self endRefreshing:0.5];
        }
        
    } else {
        SHOWMBProgressHUD(nil, SN_Text(@"更新中..."), nil, NO, 2.0);
        [self endRefreshing:0.5];
    }
    
    // 同步下拉刷新数据完成回调
    KK_BLESend.updateDataEndBlock = ^{
        if (_isReload == YES) {
            [self endRefreshing:0.5];
            _isReload = NO;
        }
    };
}

- (void)endRefreshing:(CGFloat)time {
    __unsafe_unretained UITableView *tableView = self.tableView;
    
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(time * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        // 结束刷新
        [tableView.mj_header endRefreshing];
    });
}

- (void)updateMJHeadView {
    _header                            = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(loadNewData)];
    _header.backgroundColor            = [UIColor colorFromHex:0x4b4b4b];
    _header.activityIndicatorViewStyle = UIActivityIndicatorViewStyleWhite;
    // 设置文字
    [_header setTitle:SN_Text(@"下拉刷新") forState:MJRefreshStateIdle];
    [_header setTitle:SN_Text(@"松开刷新") forState:MJRefreshStatePulling];
    [_header setTitle:SN_Text(@"加载 ...") forState:MJRefreshStateRefreshing];
    
    // 设置字体
    _header.stateLabel.font           = [UIFont systemFontOfSize:15];
    _header.lastUpdatedTimeLabel.font = [UIFont systemFontOfSize:14];
    if (SN_USER.lastUpdateTime.length > 0) {
        _header.lastUpdatedTimeLabel.text = [NSString stringWithFormat:@"%@:%@", SN_Text(@"上次更新"), SN_USER.lastUpdateTime];
    } else {
        _header.lastUpdatedTimeLabel.text = [NSString stringWithFormat:@"%@:%@", SN_Text(@"上次更新"), [[NSDate date]dateToString]];
    }
    // 设置颜色
    _header.stateLabel.textColor           = SNCOLORGRAY;
    _header.lastUpdatedTimeLabel.textColor = SNCOLORGRAY;
    // 设置刷新控件
    _tableView.mj_header                          = _header;
    _tableView.mj_header.automaticallyChangeAlpha = YES;
}

- (void)initWithHeadView {
    _bgView = [[UIView alloc] init];
    CGFloat headViewHeight = 0;
    headViewHeight                           = FitSimpleSize(237, 255, 270, 280, 270);
    headViewHeight                           = headViewHeight - 10;
    _headView                                = [[UIScrollView alloc]init];
    _headView.frame                          = CGRectMake(0, 0, HHHWIDTH, headViewHeight);
    _bgView.frame                            = CGRectMake(0, 0, HHHWIDTH, headViewHeight +footHeight);
    _headView.pagingEnabled                  = YES;
    _headView.delegate                       = self;
    _headView.backgroundColor                = [UIColor clearColor];
    _headView.contentSize                    = CGSizeMake(HHHWIDTH*3, 0);
    _headView.contentOffset                  = CGPointMake(HHHWIDTH, 0);
    _headView.showsHorizontalScrollIndicator = NO;
    [_bgView addSubview:_headView];
    [self initstepCircle]; //初始化圆圈
}

- (void)initstepCircle {
    _leftView   = [[SNHomeHeadView alloc]initWithFrame:CGRectMake(0, 10, HHHWIDTH, _headView.height)];
    _centerView = [[SNHomeHeadView alloc]initWithFrame:CGRectMake(HHHWIDTH, 10, HHHWIDTH, _leftView.height)];
    DEF_WEAKSELF_(SNHomePageViewController)
    _centerView.hiddenBlock = ^(BOOL hidden) {
        weakSelf.leftView.hidden  = hidden;
        weakSelf.rightView.hidden = hidden;
    };
    _rightView = [[SNHomeHeadView alloc]initWithFrame:CGRectMake(HHHWIDTH*2, 10, HHHWIDTH, _leftView.height)];
    [_headView addSubview:_leftView];
    [_headView addSubview:_centerView];
    [_headView addSubview:_rightView];
    [self SNBecomeActive];
    [self initWeatherUI];
}

- (void)initWeatherUI {
    _weatherBakeView = [[UIView alloc] init];
    
    _weatherBakeView.frame = SNFRAME(0, _centerView.bottom, HHHWIDTH, 30);
    [_bgView addSubview:_weatherBakeView];
    CGFloat       height     = -10.0;
    SNCustomLabel *infolabel = [[SNCustomLabel alloc] initWithFrame:SNFRAME(10, 0 +height, 200, 20)];
    
    infolabel.text          = SN_Text(@"你的健康");
    infolabel.font          = SNFITFONT(16);
    infolabel.textAlignment = NSTextAlignmentLeft;
    
    _weatherLabel               = [[SNCustomLabel alloc] initWithFrame:SNFRAME(HHHWIDTH-HHHWIDTH/4 -5, infolabel.top, HHHWIDTH/4, 20)];
    _weatherLabel.font          = SNFONTMIN(13);
    _weatherLabel.textAlignment = NSTextAlignmentCenter;
    
    _weatherImageV       = [[UIImageView alloc] init];
    _weatherImageV.frame = SNFRAME(_weatherLabel.left - 5, infolabel.centerY -11, 22, 22);
    [self updateWeateherTextLabel];
    
    _weatherTypeLabel = [[SNCustomLabel alloc] initWithFrame:SNFRAME(_weatherImageV.left -200-5, infolabel.top, 200, 20)];
    
    _weatherTypeLabel.text          = _weatherType;
    _weatherTypeLabel.font          = SNFONTMIN(13);
    _weatherTypeLabel.textAlignment = NSTextAlignmentRight;
    [_weatherBakeView addSubview:_weatherImageV];
    [_weatherBakeView addSubview:_weatherLabel];
    [_weatherBakeView addSubview:_weatherTypeLabel];
    [_weatherBakeView addSubview:infolabel];
    
    [self initOtherUi];
}

- (void)initOtherUi {

    if (_footView) {
        [_footView removeFromSuperview];
        _footView = nil;
    }
    
    // 健康食谱
    _footView                   = [[UIView alloc] init];
    
    if (SN_USER.isSupporFood == YES) {
        _footView.frame             = SNFRAME(FitW(13), _weatherBakeView.bottom - 15, HHHWIDTH - 2*FitW(13), footHeight - 20);
    } else {
        _footView.frame             = SNFRAME(FitW(13), _weatherBakeView.bottom - 15, HHHWIDTH - 2*FitW(13), 0);
    }
    _footView.layer.borderWidth = 0.5;
    _footView.layer.borderColor = SNCOLORGRAYLINE.CGColor;
    
    if (SN_USER.isSupporFood == YES) {
        [_bgView addSubview:_footView];
        _bgView.frame                            = CGRectMake(0, 0, HHHWIDTH, _headView.frame.size.height + footHeight);
    } else {
        _bgView.frame                            = CGRectMake(0, 0, HHHWIDTH, _headView.frame.size.height + 30);
    }
    
    UIView *line = [[UIView alloc] initWithFrame:SNFRAME(_footView.width/2.0, 10, 1, _footView.height - 20)];
    line.backgroundColor = [UIColor grayColor];
    line.alpha           = 0.2;
    [_footView addSubview:line];
    
    UIButton *foodDetailBtn = [[UIButton alloc] init];
    foodDetailBtn.frame = SNFRAME(0, 0, _footView.width/2.0, _footView.height);
    [foodDetailBtn addTarget:self action:@selector(foodDetailBtnClick) forControlEvents:UIControlEventTouchUpInside];
    [_footView addSubview:foodDetailBtn];
    
    //    [foodDetailBtn addTarget:self action:@selector(buttonClickDraw:) forControlEvents:UIControlEventTouchDown];
    //    [foodDetailBtn addTarget:self action:@selector(buttonClickDrawOut:) forControlEvents:UIControlEventTouchUpOutside];
    
    CGFloat     imageWidth     = _footView.height/2.5;
    UIImageView *foodImageView = [[UIImageView alloc]initWithFrame:SNFRAME(foodDetailBtn.centerX -imageWidth/2, foodDetailBtn.top + 20, imageWidth, imageWidth)];
    foodImageView.image = SNIMAGENAME(@"用餐");
    [foodDetailBtn addSubview:foodImageView];
    
    _foodValuelabel                           = [[UILabel alloc] initWithFrame:SNFRAME(0, foodImageView.bottom +10, foodDetailBtn.width, 20)];
    _foodValuelabel.font                      = SNFONT(SNFITFONTSIZE(20));
    _foodValuelabel.minimumScaleFactor        = 0.5;
    _foodValuelabel.adjustsFontSizeToFitWidth = YES;
    _foodValuelabel.textAlignment             = NSTextAlignmentCenter;
    [foodDetailBtn addSubview:_foodValuelabel];
    [self updateFoodValueLabel];
    
    UILabel *detailLabel = [[UILabel alloc]initWithFrame:SNFRAME(0, _footView.height -FitW(30), _foodValuelabel.width, 20)];
    detailLabel.text          = SN_Text(@"已摄入热量");
    detailLabel.textAlignment = NSTextAlignmentCenter;
    detailLabel.font          = SNFONT(SNFITFONTSIZE(14));
    [foodDetailBtn addSubview:detailLabel];
    
    _foodSetView1 = [[UIButton alloc] init];
    _foodSetView1.frame = SNFRAME(_footView.width/2.0 +10, 15, _footView.width/2.0-20, _footView.height/2.0 -5);
    _foodSetView1.tag   = 1;
    [_foodSetView1 addTarget:self action:@selector(foodSetViewSetting:) forControlEvents:UIControlEventTouchUpInside];
    [_footView addSubview:_foodSetView1];
    _foodSetView1.backgroundColor    = FOODCOLOR;
    _foodSetView1.titleLabel.font    = SNFONT(SNFITFONTSIZE(15));
    _foodSetView1.layer.cornerRadius = 5.0;
    [_foodSetView1 setTitle:SN_Text(@"记录我吃了什么") forState:UIControlStateNormal];
    [_foodSetView1 setTitle:SN_Text(@"记录我吃了什么") forState:UIControlStateHighlighted];
    _foodSetView1.titleLabel.adjustsFontSizeToFitWidth = YES;
    [_foodSetView1 setTitleColor:[UIColor lightGrayColor] forState:UIControlStateHighlighted];
    _foodSetView1.titleEdgeInsets = UIEdgeInsetsMake(-15, 0, 0, 0);
    
    _foodEatInfoLabel      = [UILabel simpleWithRect:SNFRAME(10, _foodSetView1.height - 25, _foodSetView1.width - 20, 20) withAlignment:NSTextAlignmentCenter withFontSize:14.0 withText:@"" withTextColor:[UIColor whiteColor]];
    _foodEatInfoLabel.font = SNFONT(SNFITFONTSIZE(14));
    [_foodSetView1 addSubview:_foodEatInfoLabel];
    
    UIButton *foodSetView2 = [[UIButton alloc] init];
    foodSetView2.frame = SNFRAME(_footView.width/2.0+10, _footView.height/2.0+ 15, _footView.width/2.0-20, _footView.height/2.0 - 15);
    [_footView addSubview:foodSetView2];
    foodSetView2.tag                = 2;
    foodSetView2.layer.cornerRadius = 5.0;
    [foodSetView2 addTarget:self action:@selector(foodSetViewSetting:) forControlEvents:UIControlEventTouchUpInside];
    
    UIImageView *imageV = [[UIImageView alloc] init];
    imageV.frame = SNFRAME(0, (foodSetView2.height- 33)/2, 33, 33);
    imageV.image = SNIMAGENAME(@"用餐设置");
    [foodSetView2 addSubview:imageV];
    
    UILabel *label2 = [UILabel simpleWithRect:SNFRAME(imageV.right + 5, imageV.top+10, foodSetView2.width - imageV.right - 5, 20) withAlignment:NSTextAlignmentLeft withFontSize:13.0 withText:SN_Text(@"我的理想体重") withTextColor:[UIColor blackColor]];
    label2.font = SNFONT(SNFITFONTSIZE(12));
    label2.adjustsFontSizeToFitWidth = YES;
    [foodSetView2 addSubview:label2];
    
    _footViewInfo                   = [[SNShadowView alloc] init];
    _footViewInfo.frame             = SNFRAME(FitW(13), _weatherBakeView.bottom - 15, HHHWIDTH - 2*FitW(13), footHeight - 20);
    _footViewInfo.layer.borderWidth = 0.5;
    _footViewInfo.layer.borderColor = SNCOLORGRAYLINE.CGColor;
    [_bgView addSubview:_footViewInfo];
    _footViewInfo.backgroundColor = [[UIColor blackColor]colorWithAlphaComponent:0.5];
    
    if (SN_USER.goal_weight == 0) {
        _footViewInfo.hidden = NO;
    } else {
        _footViewInfo.hidden = YES;
    }
    
    UIButton *buttonClick = [[UIButton alloc] init];
    buttonClick.frame                                = SNFRAME(40, _footViewInfo.height/2 -30, _footViewInfo.width - 80, 60);
    buttonClick.backgroundColor                      = FOODCOLOR;
    buttonClick.titleLabel.adjustsFontSizeToFitWidth = YES;
    [buttonClick setTitle:SN_Text(@"开始我的美食享“瘦”之旅") forState:UIControlStateNormal];
    [buttonClick setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [buttonClick setTitleColor:[UIColor grayColor] forState:UIControlStateHighlighted];
    [buttonClick addTarget:self action:@selector(foodViewbuttonClick) forControlEvents:UIControlEventTouchUpInside];
    [_footViewInfo addSubview:buttonClick];
}

- (void)foodViewbuttonClick {
    SNFoodSettingViewController *vc = [[SNFoodSettingViewController alloc]init];
    
    [self.navigationController pushViewController:vc animated:YES];
}

- (void)foodSetViewSetting:(UIButton *)sender {
    if (sender.tag == 1) {
        // 第一次需要设置目标体重
        if (SN_USER.goal_weight == 0) {
            SNFoodSettingViewController *vc = [[SNFoodSettingViewController alloc]init];
            [self.navigationController pushViewController:vc animated:YES];
        } else {
            SNFoodViewController *vc = [[SNFoodViewController alloc] init];
            [self.navigationController pushViewController:vc animated:YES];
        }
    }
    if (sender.tag == 2) {
        SNFoodSettingViewController *vc = [[SNFoodSettingViewController alloc]init];
        [self.navigationController pushViewController:vc animated:YES];
    }
}

- (void)foodDetailBtnClick {
    SNFoodDetailViewController *vc = [[SNFoodDetailViewController alloc] init];
    
    [self.navigationController pushViewController:vc animated:YES];
}

- (void)cheakHealthyClick {
    if ([_currentDateLabel.text isEqualToString:SN_Text(@"今天")]) {
        SNHealthyCheckVc *vc = [[SNHealthyCheckVc alloc] init];
        [self.navigationController pushViewController:vc animated:YES];
    } else {
        SHOWMBProgressHUD(nil, SN_Text(@"返回今天才能体检"), nil, NO, 1.0);
    }
}

- (UIImage *)backImage {
    UIImage *image       = [[UIImage alloc]init];
    NSArray *sunArr      = @[@"100"];
    NSArray *cloudArr    = @[@"101", @"102", @"103", @"101", @"101", @"201", @"202", @"203", @"204"];
    NSArray *snowArr     = @[@"400", @"401", @"402", @"403", @"404", @"405", @"406", @"407", ];
    NSArray *overcastArr = @[@"104", @"200", @"205", @"206", @"207", @"208", @"210", @"500", @"501", @"502", @"503", @"504", @"507", @"508"];
    NSArray *rainArr     = @[@"209", @"211", @"212", @"213", @"300", @"301", @"302", @"304", @"305", @"306", @"307", @"308", @"309", @"310", @"311", @"312", @"313"];
    NSArray *nonArr      = @[@"900", @"901", @"902"];
    
    image        = UIImageNamed(@"无");
    _weatherType = SN_Text(@"无");
    if ([sunArr containsObject:KK_WeatherModel.weatherCode]) {
        image        = UIImageNamed(@"晴天");
        _weatherType = SN_Text(@"晴");
    } else if ([cloudArr containsObject:KK_WeatherModel.weatherCode]) {
        image        = UIImageNamed(@"多云");
        _weatherType = SN_Text(@"多云");
    } else if ([snowArr containsObject:KK_WeatherModel.weatherCode]) {
        image        = UIImageNamed(@"雪");
        _weatherType = SN_Text(@"雪");
    } else if ([overcastArr containsObject:KK_WeatherModel.weatherCode]) {
        image        = UIImageNamed(@"6阴天");
        _weatherType = SN_Text(@"阴");
    } else if ([rainArr containsObject:KK_WeatherModel.weatherCode]) {
        image        = UIImageNamed(@"雨");
        _weatherType = SN_Text(@"雨");
    } else if ([nonArr containsObject:KK_WeatherModel.weatherCode]) {
    }
    return image;
}

#pragma mark - 创建日历
- (void)crectCalendar {
    [_calendarView popupWithtype:PopupViewOption_colorLump succeedBlock:^(UIView *View)
     {
         if (_edit == YES) {
             [self editButtonClick:_editButton];
         }
         View.center = CGPointMake(HHHWIDTH/2, HHHHEIGHT/2 +33 - FitSimpleSize(50, 50, 90, 125, 145));
         _calendarView.hidden = NO;
         [_CalendarViewSub reloadViewData];
     }              dismissBlock:^(UIView *View)
     {
         _calendarView.hidden = YES;
     }];
}

- (void)backButtonClick {
    NSUInteger nowCount = [NSDate compareDate:[NSDate date] withAnotherDay:SN_PublicClass.selectDate];
    
    if (nowCount == 0) {
        return;
    }
    SN_PublicClass.selectDate = [NSDate date];
    [self updateAlldata];
    [self updateTableView];
}

// 分享
- (void)shareButtonClick {
    UIGraphicsBeginImageContext(CGSizeMake(screenWidth, screenHeight));
    
    [[UIApplication sharedApplication].delegate.window.layer renderInContext:UIGraphicsGetCurrentContext()];
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    NSMutableArray *items = [[NSMutableArray alloc] init];
    [items addObject:image];
    
    UIActivityViewController *activityViewController = [[UIActivityViewController alloc] initWithActivityItems:items applicationActivities:nil];
    NSMutableArray           *excludedActivityTypes  = [NSMutableArray arrayWithArray:@[
                                                                                        UIActivityTypeMessage, UIActivityTypeMail, UIActivityTypePrint, UIActivityTypeCopyToPasteboard, UIActivityTypeAssignToContact, UIActivityTypeSaveToCameraRoll, UIActivityTypeAddToReadingList, UIActivityTypePostToFlickr, UIActivityTypePostToVimeo, UIActivityTypePostToTencentWeibo, UIActivityTypeAirDrop,
                                                                                        UIActivityTypeOpenInIBooks]];
    activityViewController.excludedActivityTypes = excludedActivityTypes;
    
    [self presentViewController:activityViewController animated:YES completion:nil];
    activityViewController.completionWithItemsHandler = ^(UIActivityType __nullable activityType, BOOL completed, NSArray *__nullable returnedItems, NSError *__nullable activityError){
    };
}

// 步数 周月年图表查看
- (void)detailChartButtonClick {
    SNStepChartVc *vc = [[SNStepChartVc alloc] init];
    
    [self.navigationController pushViewController:vc animated:YES];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)touchesEnded:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return _dataArray.count/2 + _dataArray.count %2;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    CGFloat row = 0;
    row = HHHWIDTH / 2.0;
    return row;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString         *identifier = @"SNHomePageTableViewCell";
    SNHomePageTableViewCell *cell       = [tableView cellForRowAtIndexPath:indexPath];
    if (nil == cell) {
        cell = [[SNHomePageTableViewCell alloc] initWithStyle:(UITableViewCellStyleDefault) reuseIdentifier:identifier];
    }
    
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    //    for (int i = 0; i < _dataArray.count; i += 2) {
    //        if (i/2 == indexPath.row) {
    //            if (i%2 == 0) {
    //                [cell updateMainCellLeft:_dataArray[i]];
    //                if (i+1 < _dataArray.count) {
    //                    [cell updateMainCellRight:_dataArray[i+1]];
    //                }
    //            }
    //        }
    //    }
    //    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    //    [cell.button addTarget:self action:@selector(homePageCellClick:) forControlEvents:UIControlEventTouchUpInside];
    //    [cell.button2 addTarget:self action:@selector(homePageCellClick:) forControlEvents:UIControlEventTouchUpInside];
    //
    //    [cell.button addTarget:self action:@selector(buttonClickDraw:) forControlEvents:UIControlEventTouchDown];
    //    [cell.button2 addTarget:self action:@selector(buttonClickDraw:) forControlEvents:UIControlEventTouchDown];
    //    [cell.button addTarget:self action:@selector(buttonClickDrawOut:) forControlEvents:UIControlEventTouchUpOutside];
    //    [cell.button2 addTarget:self action:@selector(buttonClickDrawOut:) forControlEvents:UIControlEventTouchUpOutside];
    return cell;
}

- (void)homePageCellClick:(UIButton *)sender {
    //    NSString *s = [NSString stringWithFormat:@"%ld", sender.tag];
    //
    //    if (s.intValue == 0) {
    //        SNSleepDetailVc *vc = [[SNSleepDetailVc alloc] init];
    //        [self.navigationController pushViewController:vc animated:YES];
    //    } else if (s.intValue == 1) {
    //        SNCheckVc *vc = [[SNCheckVc alloc] init];
    //        [self.navigationController pushViewController:vc animated:YES];
    //    } else if (s.intValue == 2) {
    //        SNHearDetailVc *vc = [[SNHearDetailVc alloc] init];
    //        [self.navigationController pushViewController:vc animated:YES];
    //    } else if (s.intValue == 3) {
    //        SNOxDetailVc *vc = [[SNOxDetailVc alloc] init];
    //        [self.navigationController pushViewController:vc animated:YES];
    //    } else if (s.intValue == 4) {
    //        SNBpDetailVc *vc = [[SNBpDetailVc alloc] init];
    //        [self.navigationController pushViewController:vc animated:YES];
    //    }
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (void)buttonClickDraw:(UIButton *)sender {
    if (_clickView) {
        [_clickView removeFromSuperview];
        _clickView = nil;
    }
    _clickView = [[SNClickEffView alloc] initWithFrame:SNFRAME(0, 0, sender.width, sender.height)];
    [sender addSubview:_clickView];
    _clickView.center = sender.center;
    [_clickView tapView];
}

- (void)buttonClickDrawOut:(UIButton *)sender {
    if (_clickView) {
        [_clickView removeFromSuperview];
        _clickView = nil;
    }
}

// 蓝牙数据更新回调
- (void)updateView:(KKBLEAcceptType)type {
    if (!_isUpdateView) {
        return;
    }
    NSInteger nowcount = [NSDate compareDate:[NSDate date] withAnotherDay:SN_PublicClass.selectDate];
    if (nowcount == 0) {
        if (!KK_BLESend.isSend) {
        }
        if (type == KKBLEAcceptTypeRealtimeSport || type == KKBLEAcceptTypeDataSport) {
            [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(delayUpdatCenter) object:nil];
            [self performSelector:@selector(delayUpdatCenter) withObject:nil afterDelay:0.5];
        }
        if (type == KKBLEAcceptTypeDataSport || type == KKBLEAcceptTypeDataSleep || type == KKBLEAcceptTypeDataHeart || type == KKBLEAcceptTypeDataOxygen || type == KKBLEAcceptTypeDataPressure) {
            [self updateTableView];
            if (SN_USER.lastUpdateTime.length > 0) {
                _header.lastUpdatedTimeLabel.text = [NSString stringWithFormat:@"%@:%@", SN_Text(@"上次更新"), SN_USER.lastUpdateTime];
            } else {
                _header.lastUpdatedTimeLabel.text = [NSString stringWithFormat:@"%@:%@", SN_Text(@"上次更新"), [[NSDate date]dateToString]];
            }
        }
    }
}


- (void)delayUpdatCenter {
    SportModel *centerModel = [SportModel getSportModelFromDBWith:SN_PublicClass.selectDate];
    
    _centerView.model = centerModel;
}

@end

